<?php

namespace App;

use DB;

class User extends Model
{
   	public $table = 't_users';

   	public function cost()
   	{
   		$fee = Order::select(DB::raw('SUM(order_amount)'))->where(['user_id' => $this->userid, 'pay_status' => 1])->value('SUM(order_amount)');
   		return $fee ? $fee : 0;
   	}

   	public function totalCost()
   	{
   		return Order::select(DB::raw('SUM(order_amount)'))->where(['user_id' => $this->userid, 'pay_status' => 1])->value('SUM(order_amount)');
   	}

   	public function totalGames()
   	{
   		$count = EveryGame::select(DB::raw('room_uuid'))->where(['user_id' => $this->userid])->groupBy('room_uuid')->get();
         return count($count);
   	}

      public function userAgent()
      {
         return $this->belongsTo('App\Agent', 'daili_id', 'id');
      }

      public function agent()
      {
         return Agent::where(['unionid' => substr($this->account, 3)])->first();
      }

      /**
       * [completeUserNum 我邀请的，没使用过抽奖机会并完成了5局游戏的用户]
       * @return [type] [description]
       */
      public function completeTaskUser()
      {
         $draw_number = 0;
         $next_user = [];
         $user_id = LotteryLog::select(DB::raw('user_id'))->where(['draw_id' => $this->userid])->get()->toArray();
         $user_id = array_column($user_id, 'user_id');
         $my_invite_users = User::where(['invite_id' => $this->userid])->whereNotIn('userid', $user_id)->get();//我邀请的没使用过抽奖的用户
         if ($my_invite_users) {
            $completeUser = [];
            foreach ($my_invite_users as $user) {
               if ($user->checkFiveGames() >= 12) {
                  $draw_number += 1;
                  $next_user = $user;
               }
            }
         }

         return [
            'draw_number' => $draw_number,
            'next_user' => $next_user
         ];
      }

      /**
       * [todayDrawNum 今日抽奖次数]
       * @return [type] [description]
       */
      public function todayDrawNum()
      {
         return lotteryLog::select(DB::raw('count(draw_id)'))->where(['draw_id' => $this->userid])->value('count(draw_id)');
      }

      /**
       * [checkFiveGames 检查用户是否完成了5局游戏]
       * @return [type] [description]
       */
      public function checkFiveGames()
      {
         return EveryGame::select(DB::raw('count(user_id)'))->where(['user_id' => $this->userid])->value('count(user_id)');
      }
}
